# -- coding: utf-8 --
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import re

headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.59",
    }
base_url = 'https://music.163.com/song?id={}'
input_data = input('请复制歌曲链接或ID到此处，并按下Enter键：')
if 'song?id'  in input_data:
    url = input_data
else:
    url = base_url.format(input_data)
option = Options()
# 下面4行是开启无头模式代码
option.add_argument('--headless')
option.add_argument('--disable-gpu')
option.add_argument("window-size=1024,768")
option.add_argument("--no-sandbox")
# 不启用无头模式注释掉这4行
driver = webdriver.Chrome(options=option)
driver.get(url)
driver.switch_to.frame(0)
driver.execute_script('window.scrollTo(0,120)')
driver.find_element_by_partial_link_text('展开').click()
lyric = driver.find_element_by_id('lyric-content').text
list1 = lyric.split('\n')
if list1[-1] == '收起' or '展开':
    del list1[-1]
lyric = '\n'.join(list1)
title = driver.find_element_by_class_name('tit').text
artist = driver.find_element_by_xpath('//p[@class="des s-fc4"]/span').get_attribute('title')
p = r"[\/\\\:\*\?\"\<\>\|]"
title = re.sub(p, ' ', title)
artist = re.sub(p, ' ', artist)
with open(title+'-'+artist+' 歌词.txt', 'w') as f:
    f.write(title+'-'+artist+' 歌词'+'\n'*3+lyric)
driver.quit()
